package org.unicat.serviceedu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.unicat.commonutils.ColorLogInfo;
import org.unicat.commonutils.ResultCode;
import org.unicat.servicebase.exceptionHandler.GuliException;
import org.unicat.serviceedu.entity.EduSubject;
import org.unicat.serviceedu.entity.excel.ExcelSubjectData;
import org.unicat.serviceedu.service.EduSubjectService;

import java.util.ArrayList;
import java.util.List;

public class ExcelSubjectListener extends AnalysisEventListener<ExcelSubjectData> {

    private EduSubjectService subjectService;

    private List<ExcelSubjectData> subjectDataList = new ArrayList<>();

    public ExcelSubjectListener() {
    }

    public ExcelSubjectListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {

        subjectDataList.add(excelSubjectData);

        if (subjectService == null) {
            throw new GuliException(ResultCode.ERROR, "文件数据为空");
        }

        //添加一级分类
        EduSubject existOneSubject = subjectService.existOneSubject(excelSubjectData.getOneSubjectName());
        //没有相同的
        if (existOneSubject == null) {
            existOneSubject = new EduSubject();
            existOneSubject.setTitle(excelSubjectData.getOneSubjectName());
            existOneSubject.setParentId("0");
            // 一级课程新添sort
            // 当前一级条目数+1
            int maxSort = subjectService.getOne(new QueryWrapper<EduSubject>()
                    .orderByDesc("sort")
                    .last("limit 1")).getSort();
            existOneSubject.setSort(maxSort + 1);

            subjectService.save(existOneSubject);

            ColorLogInfo.colorLog("", ColorLogInfo.YELLOW, 1, "添加了新的一级课程:");
            ColorLogInfo.colorLog("", ColorLogInfo.YELLOW, 1, existOneSubject.getTitle());
        }

        //获取一级分类id值
        String pid = existOneSubject.getId();

        //添加二级分类
        EduSubject existTwoSubject = subjectService.existTwoSubject(excelSubjectData.getTwoSubjectName(), pid);
        if (existTwoSubject == null) {
            existTwoSubject = new EduSubject();
            existTwoSubject.setTitle(excelSubjectData.getTwoSubjectName());
            existTwoSubject.setParentId(pid);
            // 二级课程新添sort
            // 当前一级条目数的sort
            existTwoSubject.setSort(existOneSubject.getSort());

            subjectService.save(existTwoSubject);

            ColorLogInfo.colorLog("添加了新的二级课程", ColorLogInfo.YELLOW, 1, existOneSubject.getTitle());
        }

    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        ColorLogInfo.colorLog("上传了新课程\n目前总计：", ColorLogInfo.CYAN, 1, subjectDataList.toString());
    }
}
